package net.hashcoding.cookbook.core.controller;

import net.hashcoding.cookbook.core.HttpMethod;
import net.hashcoding.cookbook.core.ServiceException;

import java.lang.reflect.Method;
import java.util.ArrayList;


/**
 * Created by Administrator on 2017/6/25.
 */
public class ControllerFactory {

    public static Controller get(Class<? extends Controller> clazz) {
        Controller controller;
        try {
            controller = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            throw ServiceException.internalError();
        }

        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            // just inject method annotated by TargetURI
            if (!method.isAnnotationPresent(TargetURI.class))
                continue;

            TargetURI targetURI = method.getAnnotation(TargetURI.class);
            String name = targetURI.name();
            HttpMethod[] requestMethods = targetURI.method();
            java.lang.reflect.Parameter[] parameters = method.getParameters();

            ArrayList<ControllerInterface.Parameter> annotatedParameters = new ArrayList<>();
            for (java.lang.reflect.Parameter parameter : parameters) {
                Parameter paramAnnotation = parameter.getAnnotation(Parameter.class);
                String parameterName = paramAnnotation.value();
                annotatedParameters.add(new ControllerInterface.Parameter(parameterName, parameter));
            }

            ControllerInterface controllerInterface = new ControllerInterface(
                    name, method, (ControllerInterface.Parameter[]) annotatedParameters.toArray());

            controller.insertInterface(name, requestMethods, controllerInterface);
        }

        return controller;
    }

}
